from django.shortcuts import render
from django.utils.deprecation import MiddlewareMixin

from system import models
from system.models import userToken
from system.utils import response_fails
from django.http import JsonResponse
from django.shortcuts import HttpResponseRedirect


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):

        paths = ['/', '/dologin/', '']

        if request.path not in paths:  # and request.path not in paths
            if not request.COOKIES.get('token'):
                print('未登录，跳转至登录页面')
                return render(request, 'login.html')

                # 如果token存在，与数据库中对比是否一致，否则跳转至登录页面；并提示该用户在其他地方已登录
            token = request.COOKIES.get('token')
            userToken = models.userToken.objects.filter(token=token)
            if not userToken:
                print('其他地方被登录，跳转至登录页面')
                # return response_fails('未登录，跳转至登录页面')
                return render(request, 'login.html', {'msg': '账户在其他地方登录，请重新登录！'})

        print(request.path)
        print(request.COOKIES.get('token'))
        return self.get_response(request)

    # def __init__(self, get_response):
    #     self.get_response = get_response
    #
    # def __call__(self, request):
    #
    #     # print(dir(request))
    #     paths = ['/','/dologin/','/','']
    #
    #     if not request.COOKIES.get('token') and request.path not in paths:# and request.path not in paths
    #         print('未登录，跳转至登录页面')
    #         # return response_fails('未登录，跳转至登录页面')
    #         return render(request, 'login.html')
    #
    #     print(request.path)
    #     print(request.COOKIES.get('token'))
    #     return self.get_response(request)
